package com.kangjia.model.m0.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.kangjia.api.report.Product;
import com.kangjia.http.HttpParam;
import com.kangjia.http.HttpRequest;
import com.kangjia.http.HttpResponse;
import com.kangjia.jasckson.DataMapper;

import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Service
@Slf4j
public class ProductService {

	@Autowired
	protected HttpRequest httpRequest;
	@Value("${product.url}")
	private String url;
	@Autowired
	private JedisPool jedisPool;
	
	public Product getProduct(String productId) {
		log.info("productId={}", productId);
		Jedis jedis = jedisPool.getResource();
		try {
			if (StringUtils.isBlank(productId)) {
				return null;
			}
			String key = "HW_PRODUCT_" + productId;
			String j = jedis.get(key);
			if (StringUtils.isNotBlank(j)) {
				return DataMapper.read(j, Product.class);
			}
			List<HttpParam> params = new ArrayList<>();
			params.add(new HttpParam("product_id", productId));
			HttpResponse response = httpRequest.form(url, params);
			String res = response.getResponse();
			if (StringUtils.isNotBlank(res)) {
				Product product = new Product();
				JSONArray jsonArray = new JSONArray(res);
				JSONObject json = null;
				if (jsonArray.length() > 0) {
					json = jsonArray.getJSONObject(0);
				}
				if (json == null) {
					return null;
				}
				if (!json.isNull("url")) {
					product.setUrl(json.getString("url"));
				}
				if (!json.isNull("imgUrl")) {
					product.setImgUrl(json.getString("imgUrl"));
				}
				if (!json.isNull("productName")) {
					product.setProductName(json.getString("productName"));
				}
				if (!json.isNull("price")) {
					product.setPrice(json.getString("price"));
				}
				if (!json.isNull("mktprice")) {
					product.setMktprice(json.getString("mktprice"));
				}
				if (!json.isNull("product_id")) {
					product.setProductId(json.getString("product_id"));
				}
				jedis.set(key, DataMapper.write(product));
				jedis.expire(key, 7200);
				return product;
			}
			return null;
		} finally {
			jedis.close();
		}
	}
	
	public String getTemp(String key, String field) {
		Jedis jedis = jedisPool.getResource();
		try {
			return jedis.hget(key, field);
		} finally {
			jedis.close();
		}
	}
}
